package com.brsya.movie.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.brsya.base.base.BaseMvpFragment;
import com.brsya.base.base.Contents;
import com.brsya.base.bean.CategoryBean;
import com.brsya.base.bean.MovieBean;
import com.brsya.base.recycler.BaseAdapter;
import com.brsya.base.recycler.BaseViewHolder;
import com.brsya.base.util.GlideUtil;
import com.brsya.base.util.LoggerUtil;
import com.brsya.base.util.StringUtil;
import com.brsya.base.util.UiUtil;
import com.brsya.movie.R;
import com.brsya.movie.activity.PlayActivity;
import com.brsya.movie.contract.CategoryContract;
import com.brsya.movie.ksAd.TestContentPageFragment;
import com.brsya.movie.ksAd.TestContentPageFragmentActivity;
import com.brsya.movie.presenter.CategoryPresenter;
import com.brsya.movie.util.StartActivityUtils;
import com.brsya.movie.widget.ScoreView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.material.appbar.AppBarLayout;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsEntryElement;
import com.kwad.sdk.api.KsFeedAd;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsScene;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/7/6  17:08
 * Description:
 * 分类筛选页面
 */
public class CategoryFragment extends BaseMvpFragment<CategoryPresenter> implements CategoryContract.View {
    private static final int ITEM_TYPE_AD = 200;
    public static final long KS_AD_ID = 9661000058L;
    //    public static final long KS_AD_ID = 9661000065L;

    private AppBarLayout ablCategoryBox;
    private TextView tvCategoryText;
    private SwipeRefreshLayout srlRefresh;
    private RecyclerView rvMovieList;
    private CommonTabLayout stlCheckedType;
    private CommonTabLayout stlCheckedTags;
    private CommonTabLayout stlCheckedArea;
    private CommonTabLayout stlCheckedYear;
    private CommonTabLayout stlCheckedSort;

    private TextView bottomTextView;


    private BaseAdapter<MovieBean> adapter;

    private List<KsFeedAd> ksFeedAds;

    private ArrayList<CustomTabEntity> typeDataList;
    private ArrayList<CustomTabEntity> tagsDataList;
    private ArrayList<CustomTabEntity> areaDataList;
    private ArrayList<CustomTabEntity> yearDataList;
    private ArrayList<CustomTabEntity> sortDataList;


    private String movieType;
    private String movieTypeName;
    private String movieTags;
    private String movieTagsName;
    private String movieArea;
    private String movieAreaName;
    private String movieYear;
    private String movieYearName;
    private String movieSort;
    private String movieSortName;

    private int pageNumber = 0;
    private KsEntryElement mEntryElement;
    private KsScene mScene;
    private List<CategoryBean> categoryBeans;


    public static CategoryFragment newInstance(String movieType, String movieSort) {

        Bundle args = new Bundle();
        if (movieType != null) {
            args.putString(Contents.INTENT_MOVIE_TYPE, movieType);
        }
        if (movieSort != null) {
            args.putString(Contents.INTENT_MOVIE_SORT, movieSort);
        }
        CategoryFragment fragment = new CategoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);

        if (args != null) {
            if (args.getString(Contents.INTENT_MOVIE_TYPE) != null) {
                movieType = args.getString(Contents.INTENT_MOVIE_TYPE);
            }
            if (args.getString(Contents.INTENT_MOVIE_SORT) != null) {
                movieSort = args.getString(Contents.INTENT_MOVIE_SORT);
            }
        }
    }

    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_category);

        rvMovieList = findViewById(R.id.rv_movie_list);
        ablCategoryBox = findViewById(R.id.abl_category_box);
        tvCategoryText = findViewById(R.id.tv_category_text);
        stlCheckedType = findViewById(R.id.stl_checked_type);
        stlCheckedTags = findViewById(R.id.stl_checked_tags);
        stlCheckedArea = findViewById(R.id.stl_checked_area);
        stlCheckedYear = findViewById(R.id.stl_checked_year);
        stlCheckedSort = findViewById(R.id.stl_checked_sort);
        srlRefresh = findViewById(R.id.srl_refresh);
    }

    @Override
    protected void initData() {

        ksFeedAds = new ArrayList<>();
        tvCategoryText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rvMovieList.smoothScrollToPosition(0);
            }
        });

        rvMovieList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rvMovieList.setAdapter(adapter = new BaseAdapter<MovieBean>() {

            //            @Override
            //            public void onAttachedToRecyclerView(@NotNull RecyclerView recyclerView) {
            //                super.onAttachedToRecyclerView(recyclerView);
            //                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            //                if (manager instanceof GridLayoutManager) {
            //                    final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            //
            //                    gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            //                        @Override
            //                        public int getSpanSize(int position) {
            //                            if (adapter.getItemViewType(position) == ITEM_TYPE_AD) {
            //                                return 3;
            //                            }
            //                            return 1;
            //                        }
            //                    });
            //                }
            //            }

            @Override
            public int getSpanSizeBtPosition(int position) {
                if (adapter.getItemViewType(position) == ITEM_TYPE_AD) {
                    return 3;
                }
                return super.getSpanSizeBtPosition(position);
            }

            @Override
            public int getItemLayoutType(int relPosition) {
                if (adapter.getDataList().get(relPosition).isAd()) {
                    return ITEM_TYPE_AD;
                }
                return super.getItemLayoutType(relPosition);
            }

            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView;
                if (viewType == BaseAdapter.TYPE_NORMAL) {
                    itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie, parent, false);
                } else {
                    itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_category_ad_box, parent, false);
                }
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieBean data) {
                if (data.isAd()) {
                    if (mEntryElement == null) {
                        return;
                    }
                    LoggerUtil.e("加载广告");
                    RelativeLayout adBox = viewHolder.findViewById(R.id.fl_ad_box);
                    adBox.removeAllViews();
                    View entryView = mEntryElement.getEntryView(getContext(), new KsEntryElement.OnFeedClickListener() {
                        @Override
                        public void handleFeedClick(int i, int i1, View view) {
                            clickItemAd(view);
                        }
                    });
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    adBox.addView(entryView, lp);
                    return;

                    //                    int position = RealPosition / 3 - 4;
                    //                    if (position < 0 || position > ksFeedAds.size()){
                    //                        return;
                    //                    }
                    //                    KsFeedAd ksFeedAd = ksFeedAds.get(position);
                    //                    ksFeedAd.setAdInteractionListener(new KsFeedAd.AdInteractionListener() {
                    //                        @Override
                    //                        public void onAdClicked() {
                    //                        }
                    //
                    //                        @Override
                    //                        public void onAdShow() {
                    //                        }
                    //
                    //                        @Override
                    //                        public void onDislikeClicked() {
                    //                            adapter.getDataList().remove(RealPosition);
                    //                            notifyDataSetChanged();
                    //                        }
                    //
                    //                        @Override
                    //                        public void onDownloadTipsDialogShow() {
                    //                        }
                    //
                    //                        @Override
                    //                        public void onDownloadTipsDialogDismiss() {
                    //                        }
                    //                    });
                    //                    View feedView = ksFeedAd.getFeedView(getContext());
                    //                    adBox.addView(feedView);
                }


                ConstraintLayout itemBox = viewHolder.findViewById(R.id.cl_movie_item_box);
                ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                ScoreView scoreView = viewHolder.findViewById(R.id.sv_score_box);

                int px = UiUtil.dpToPx(getContext(), 1);
                int position = RealPosition;
                for (int i = 0; i < RealPosition; i++) {
                    if (adapter.getDataList().get(i).isAd()) {
                        position--;
                    }
                }
                switch (position % 3) {
                    case 0:
                        itemBox.setPadding(
                                0,
                                itemBox.getPaddingTop(),
                                2 * px,
                                itemBox.getPaddingBottom()
                        );
                        break;
                    case 1:
                        itemBox.setPadding(
                                px,
                                itemBox.getPaddingTop(),
                                px,
                                itemBox.getPaddingBottom()
                        );
                        break;
                    case 2:
                        itemBox.setPadding(
                                2 * px,
                                itemBox.getPaddingTop(),
                                0,
                                itemBox.getPaddingBottom()
                        );
                        break;
                }

                tvMovieTitle.setText(data.getName());
                GlideUtil.load(ivMovieImg, data.getCoverUrl());
                scoreView.setScore(data.getDoubanScore());
            }
        });

        adapter.setItemViewClickListener(new BaseAdapter.OnItemViewClickListener<MovieBean>() {
            @Override
            public void onItemClick(int position, MovieBean data, View itemView) {
                if (data.isAd()) {

                    clickItemAd(itemView);
                    return;
                }
                // 播放页面
                Intent intent = new Intent(getActivity(), PlayActivity.class);
                intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data);
                startActivity(intent);
            }
        });

        rvMovieList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (UiUtil.isSlideToBottom(recyclerView) && ablCategoryBox.getVisibility() == View.VISIBLE) {
                    getMovieList(false);
                }
            }
        });
        View bottomView = LayoutInflater.from(getContext()).inflate(R.layout.item_no_more_data, null, false);
        bottomTextView = bottomView.findViewById(R.id.tv_no_more_data_text);
        adapter.setBottomView(bottomView);


        srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getMovieList();
            }
        });


        ablCategoryBox.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int totalScrollRange = appBarLayout.getTotalScrollRange();
                if (0 == totalScrollRange + verticalOffset) {
                    tvCategoryText.setVisibility(View.VISIBLE);
                } else {
                    tvCategoryText.setVisibility(View.GONE);
                }
            }
        });

        typeDataList = new ArrayList<>();
        tagsDataList = new ArrayList<>();
        areaDataList = new ArrayList<>();
        yearDataList = new ArrayList<>();
        sortDataList = new ArrayList<>();

        stlCheckedType.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = typeDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieType = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieTypeName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                tagsDataList.clear();

                for (CategoryBean categoryBean : categoryBeans) {
                    if ("type".equals(categoryBean.getCode())) {
                        int selectIndex = 0;
                        CategoryBean.ChailDTO chailDTO1 = new CategoryBean.ChailDTO();
                        chailDTO1.setCategoryName("全部");
                        chailDTO1.setCode("");
                        tagsDataList.add(chailDTO1);
                        if (position == 0) {
                            for (int i = 0; i < categoryBean.getChail().size(); i++) {
                                tagsDataList.addAll(categoryBean.getChail().get(i).getChail());
                            }
                        } else {
                            tagsDataList.addAll(categoryBean.getChail().get(position - 1).getChail());
                        }
                    }
                }
                movieTags = "";
                stlCheckedTags.setCurrentTab(0);
                stlCheckedTags.setTabData(tagsDataList);
                stlCheckedTags.notifyDataSetChanged();
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedTags.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = tagsDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieTags = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieTagsName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedArea.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = areaDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieArea = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieAreaName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedYear.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = yearDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieYear = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieYearName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        stlCheckedSort.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                CustomTabEntity customTabEntity = sortDataList.get(position);
                if (customTabEntity instanceof CategoryBean.ChailDTO) {
                    movieSort = ((CategoryBean.ChailDTO) customTabEntity).getCode();
                    movieSortName = ((CategoryBean.ChailDTO) customTabEntity).getCategoryName();
                }
                getMovieList();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        presenter.getCategory();

    }

    private void clickItemAd(View view) {
        StartActivityUtils.ActivityStartParam param = new StartActivityUtils.ActivityStartParam();
        param.mActivity = getActivity();
        param.mTargetActivityCls = TestContentPageFragmentActivity.class;
        param.mSourceView = view;
        if (mScene != null) {
            Bundle bundle = new Bundle();
            bundle.putLong(TestContentPageFragment.KEY_POS_ID, mScene.getPosId());
            param.mExtraParams = bundle;
        }
        StartActivityUtils.startActivityForResult(0, param);
    }

    @Override
    public void showLoading() {
        super.showLoading();
        srlRefresh.setRefreshing(true);
        bottomTextView.setText(getString(R.string.list_load_more_data));
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        srlRefresh.setRefreshing(false);
    }


    private void getMovieList() {
        getMovieList(true);
    }

    private void getMovieList(boolean isFirst) {
        StringBuffer title = new StringBuffer();
        if (StringUtil.isEmpty(movieTypeName)) {
            title.append("全部");
        } else {
            title.append(movieTypeName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieTagsName)) {
            title.append("全部");
        } else {
            title.append(movieTagsName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieAreaName)) {
            title.append("全部");
        } else {
            title.append(movieAreaName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieYearName)) {
            title.append("全部");
        } else {
            title.append(movieYearName);
        }
        title.append(" - ");
        if (StringUtil.isEmpty(movieSortName)) {
            title.append("全部");
        } else {
            title.append(movieSortName);
        }
        title.append(" - ");
        if (title.length() > 2) {
            title.delete(title.length() - 3, title.length());
            tvCategoryText.setText(title);
        } else {
            tvCategoryText.setText("-");
        }
        if (isFirst) {
            pageNumber = 1;

            adapter.clearData();
        } else {
            pageNumber++;
        }
        presenter.getMovieList(pageNumber, movieType, movieTags, movieArea, movieYear, movieSort);
    }


    @Override
    public void showCategory(List<CategoryBean> categoryBeans) {
        this.categoryBeans = categoryBeans;
        updateTags(categoryBeans);
        ablCategoryBox.setVisibility(View.VISIBLE);

        getMovieList();
    }

    private void updateTags(List<CategoryBean> categoryBeans) {
        for (CategoryBean categoryBean : categoryBeans) {
            switch (categoryBean.getCode()) {
                case "type":
                    movieType = initCheckedData(stlCheckedType, typeDataList, categoryBean.getChail(), movieType);
                    List<CategoryBean.ChailDTO> allTags = new ArrayList<>();
                    for (CategoryBean.ChailDTO chailDTO : categoryBean.getChail()) {
                        allTags.addAll(chailDTO.getChail());
                    }
                    movieTags = initCheckedData(stlCheckedTags, tagsDataList, allTags, movieTags);
                    break;
                case "tags":
                    //                    movieTags = initCheckedData(stlCheckedTags, tagsDataList, categoryBean.getChail(), movieTags);
                    break;
                case "area":
                    movieArea = initCheckedData(stlCheckedArea, areaDataList, categoryBean.getChail(), movieArea);
                    break;
                case "year":
                    movieYear = initCheckedData(stlCheckedYear, yearDataList, categoryBean.getChail(), movieYear);
                    break;
                case "sort":
                    movieSort = initCheckedData(stlCheckedSort, sortDataList, categoryBean.getChail(), movieSort);
                    break;
            }
        }
    }

    private void loadKsAd() {

        int width = getResources().getDisplayMetrics().widthPixels;
        LoggerUtil.e("加载入口组件: " + width);
        mScene = new KsScene.Builder(KS_AD_ID).width(width).build();
        KsAdSDK.getLoadManager().loadEntryElement(mScene, new KsLoadManager.EntryElementListener<KsEntryElement>() {
            @Override
            public void onError(int i, String s) {

                LoggerUtil.e("加载入口组件失败: " + i + "--: " + s);
            }

            @Override
            public void onEntryLoad(@Nullable KsEntryElement entryElemet) {
                if (entryElemet != null) {
                    mEntryElement = entryElemet;
                    List<MovieBean> dataList = adapter.getDataList();
                    //                    int position = 12;
                    //                    if (position < dataList.size()) {
                    //                        MovieBean movieBean = new MovieBean();
                    //                        movieBean.setAd(true);
                    //                        dataList.add(position, movieBean);
                    //                    }
                    for (int i = 0; i < dataList.size(); i++) {
                        MovieBean movieBean = dataList.get(i);
                        if (movieBean.isAd()) {
                            adapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        });


        //        KsScene scene = new KsScene.Builder(KS_AD_ID) // 此为测试posId，请联系快⼿平台申请正式posId
        //                .width(width)
        //                .adNum(5) // ⽀持返回多条⼴告，默认1条，最多5条，参数范围1-5
        //                .build();
        //        ksFeedAds.clear();
        //        KsAdSDK.getLoadManager()
        //                .loadConfigFeedAd(scene, new KsLoadManager.FeedAdListener() {
        //                    @Override
        //                    public void onError(int i, String s) {
        //                        LoggerUtil.e("加载入口组件失败: " + i + "--: " + s );
        //                    }
        //
        //                    @Override
        //                    public void onFeedAdLoad(@Nullable List<KsFeedAd> adList) {
        //                        if (adList == null || adList.isEmpty()) {
        //                            return;
        //                        }
        //                        for (KsFeedAd ksFeedAd : adList) {
        //                            if (ksFeedAd == null) {
        //                                continue;
        //                            }
        //                            ksFeedAds.add(ksFeedAd);
        //                        }
        //                        List<MovieBean> dataList = adapter.getDataList();
        //                        for (int i = 0; i < ksFeedAds.size(); i++) {
        //                            int position = (i + 4) * 3;
        //                            if (position < dataList.size()){
        //                                MovieBean movieBean = new MovieBean();
        //                                movieBean.setAd(true);
        //                                dataList.add(position, movieBean);
        //                            }
        //                        }
        //                        adapter.notifyDataSetChanged();
        //                    }
        //                });
    }

    private String initCheckedData(CommonTabLayout view, ArrayList<CustomTabEntity> dataList
            , List<CategoryBean.ChailDTO> dataRequest, String selectStr) {
        if (dataList.size() > 0) {
            dataList.clear();
        }
        int selectIndex = 0;
        CategoryBean.ChailDTO chailDTO1 = new CategoryBean.ChailDTO();
        chailDTO1.setCategoryName("全部");
        chailDTO1.setCode("");
        dataList.add(chailDTO1);
        if (selectStr != null) {
            for (int i = 0; i < dataRequest.size(); i++) {
                CategoryBean.ChailDTO chailDTO = dataRequest.get(i);
                if (selectStr.equals(chailDTO.getCode())) {
                    selectIndex = i + 1;
                }
                dataList.add(chailDTO);
            }
        } else {
            dataList.addAll(dataRequest);
        }
        if (dataList.size() > 0) {
            view.setTabData(dataList);
            int select = 0;
            if (view.getTabCount() > selectIndex) {
                select = selectIndex;
            }
            view.setCurrentTab(select);
            if (dataList.get(select) instanceof CategoryBean.ChailDTO) {
                return ((CategoryBean.ChailDTO) dataList.get(select)).getCode();
            }
        }
        view.setVisibility(View.GONE);
        return selectStr;
    }

    @Override
    public void showMovieList(List<MovieBean> movieBeans) {
        if (pageNumber == 1) {
            adapter.setDataList(movieBeans);
            loadKsAd();
        } else {
            adapter.addData(movieBeans);
        }
        MovieBean movieBean = new MovieBean();
        movieBean.setAd(true);
        adapter.addData(movieBean);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showNoMore() {
        bottomTextView.setText(getString(R.string.list_no_more_data));
    }

    @Override
    protected void initPresenter() {
        presenter = new CategoryPresenter();
        presenter.attachView(this);
    }


}
